

package com.kimo.shop.admin.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kimo.shop.bean.model.WebConfig;
import com.kimo.shop.common.annotation.SysLog;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.service.WebConfigService;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author kimo-taozhouchuan
 * @date 2021-02-20 09:44:42
 */
@RestController
@AllArgsConstructor
@ConditionalOnProperty(prefix = "kimo", name = "expose.permission", havingValue = "true", matchIfMissing = true)
@RequestMapping("/sys/webConfig/operate")
public class WebConfigAddUpDelController {

    private final WebConfigService webConfigService;

    /**
     * 新增
     *
     * @param webConfig
     * @return 是否新增成功
     */
    @SysLog("新增")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys:webConfig:save')")
    public ResponseEntity<Boolean> save(@RequestBody @Valid WebConfig webConfig) {
        updateState(webConfig);
        return ResponseEntity.ok(webConfigService.save(webConfig));
    }

    /**
     * 修改
     *
     * @param webConfig
     * @return 是否修改成功
     */
    @SysLog("修改")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys:webConfig:update')")
    public ResponseEntity<Boolean> updateById(@RequestBody @Valid WebConfig webConfig) {
        WebConfig webConfigDb = webConfigService.getById(webConfig.getId());
        boolean isClose = Objects.equals(webConfigDb.getIsActivity(),1) && Objects.equals(webConfig.getIsActivity(),0);
        int count = webConfigService.count(new LambdaUpdateWrapper<WebConfig>().eq(WebConfig::getIsActivity, 1).eq(WebConfig::getConfigType,webConfig.getConfigType()));
        if(count == 1 && isClose){
            // 请至少开启一个配置后再关闭当前配置
            throw new KimoShopBindException("kimo.web.config.check");
        }
        updateState(webConfig);
        return ResponseEntity.ok(webConfigService.updateById(webConfig));
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return 是否删除成功
     */
    @SysLog("删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys:webConfig:delete')")
    public ResponseEntity<Boolean> removeById(@PathVariable Integer id) {
        WebConfig webConfig = webConfigService.getById(id);
        if (webConfig.getIsActivity() == 1) {
            // 激活状态则移除缓存
            webConfigService.removeActivityWebConfig(webConfig.getConfigType());
        }
        return ResponseEntity.ok(webConfigService.removeById(id));
    }



    /**
     * 开启一个配置，其他配置则关闭
     *
     * @param webConfig 新增或修改后的对象
     */
    public void updateState(WebConfig webConfig) {
        // 关闭其他配置
        if (1 == webConfig.getIsActivity()) {
            webConfigService.update(new LambdaUpdateWrapper<WebConfig>()
                    .eq(WebConfig::getConfigType, webConfig.getConfigType())
                    .eq(WebConfig::getIsActivity, 1)
                    .set(WebConfig::getIsActivity, 0));
        }
        // 移除缓存
        webConfigService.removeActivityWebConfig(webConfig.getConfigType());
    }
}
